 

package c.x.jy.api.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import c.x.jy.api.utils.JwtUtils;
import c.x.jy.common.annotation.Login;
import c.x.jy.common.exception.RRException;
import c.x.jy.dao.entity.SysUserEntity;
import c.x.jy.service.redis.Cache;
import c.x.jy.service.service.SysUserService;
/**
 * 权限(Token)验证
 */
@Component
public class  AuthorizationInterceptor extends org.springframework.web.servlet.handler.HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private   SysUserService sysUserService;
    
	@Autowired
	private Cache redisUtils;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new RRException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        Long userid=jwtUtils.getLoginUserId(token);
        if(userid == null  ){
            throw new RRException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
         
        
        SysUserEntity user=              sysUserService.selectCacheById( userid);
 
		  if(user == null  ){ 
			  System.out.println("登陆失效，请重新登录");
		      throw new RRException("登陆失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
			  }
	 
        //账号锁定
        if(user.getStatus() == 0){
        	  System.out.println("账号已被锁定,请联系管理员");
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
    //    user.setPassword(null);
    //    user.setSalt(null);
    //   redisUtils.set(USER_KEY+":"+userid, user, 60*10l);
        //设置userId到request里，后续根据userId，获取用户信息
 //  request.setAttribute(token, user);

        return true;
    }
}
